<template>
  <div class="sel-eva-posite-container">
    <el-dialog title="选择评价岗位"
               @close="closeAdd"
               :visible.sync="dialogTableVisible"
               width="80%"
               :append-to-body="true">
      <el-form :model="requestParams"
               ref="requestParams"
               label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="被评价岗位为:">
              <span>{{requestParams.job_name}}({{requestParams.person_count}}人)</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="互评"
                          class="margin-style">
              <el-checkbox v-model="requestParams.eva_person"
                           true-label="1"
                           false-label="0">内部互评(不包含本人)</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24"
                  class="divide-style">
            <el-divider></el-divider>
            <p>其余部门评价岗位</p>
          </el-col>
          <el-col :span="6"
                  class="left-tree">
            <!-- 人员库组织架构树 -->
            <LibraryPeOrgTree :assignedNode.sync="assignNode"
                              :rightMenu="false"
                              :assignedTemplateNode.sync="assignTemplateNode"
                              :assignedPermissionNode.sync="assignPermissionNode"
                              :curMenu.sync="selectedNode"></LibraryPeOrgTree>
          </el-col>
          <el-col :span="18">
            <div class="title-style">
              <span>岗位情况</span>
              <el-button type="primary"
                         @click="joinClick">参与</el-button>
            </div>

            <!-- @selection-change='handleSelectionChange' -->
            <el-table :highlight-current-row="true"
                      border
                      ref="multipleTable"
                      :row-key="getRowKeys"
                      @selection-change="selectChange"
                      :header-cell-style="{ background: '#f5f5f5' }"
                      :data="addEvaluateList.list">
              <el-table-column type="selection"
                               :reserve-selection="true"
                               width="55">
              </el-table-column>

              <el-table-column type="index"
                               label="序号"
                               sortable
                               align="center"
                               width="80"
                               show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="job_name"
                               label="岗位"
                               align="center"
                               show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="管理层级"
                               width="100"
                               prop="manage_level"
                               align="center"
                               show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="人员"
                               show-overflow-tooltip
                               prop="person_name"
                               align="center">
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24"
                  class="botttom-box">
            <el-pagination @current-change="handleAddPageChange"
                           @size-change="handleAddSizeChange"
                           :current-page="requestParam.page"
                           :page-size="requestParam.page_size"
                           layout="total,sizes,prev, pager, next, jumper"
                           background
                           :total="addEvaluateList.total_count"
                           align="center">
            </el-pagination>
            <el-col :span="18"
                    :offset="6">
              <p class="judge-job-person">评价岗位人员</p>
              <div class="ul-box-style">
                <ul>
                  <li v-for="(item,i) in selPersonArr"
                      :key="i">
                    <p>{{item.organ_name}}-{{item.job_name}}-{{item.person_name}}</p><span @click="onDelClick(item,i)">x</span>
                  </li>
                </ul>
              </div>
              <div class="oper-button">
                <el-button @click="closeAdd">取消</el-button>
                <el-button type="primary"
                           @click="closeAdd">上一步</el-button>
                <el-button type="primary"
                           @click="onSure">确定</el-button>
              </div>
            </el-col>
          </el-col>
        </el-row>
        <span slot="footer"
              class="dialog-footer">
          <el-button type="primary"
                     @click="saveAddEvaluate">确 定</el-button>
          <el-button @click="cancelEvaluate">取 消</el-button>

        </span>

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { accountApi } from '@/services/CompanySetting'
import LibraryPeOrgTree from './LibraryPeOrgTree'
import { backEvaluateApi } from '@/services/ProjectCenter'
export default {
  components: {
    LibraryPeOrgTree
  },
  props: {
    personRequestParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    childDialog: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data () {
    return {
      multipleArr: [],//当前回显的
      selPersonArr: [],//选中的人员-所有
      requestParam: {
        node_id: '',//节点主键值
        node_type: '',//树节点类型
        no_job_id: '',//不显示属于当前岗位id的用户列表，用户岗位添加时的用户列表
        comp_id: '',
        is_page: 1,
        page: 1,
        page_size: 10,
      },
      requestParams: {
        job_name: '',//被评价岗位
        eva_person: 0,//默认是不包含自己
      },
      // 当前选择的组织树节点数据
      selectedNode: {},
      // 右键分配权限时选中的节点
      assignPermissionNode: {},
      // 右键分配模板时选中的节点
      assignTemplateNode: {},
      // 右键分配人员时选中的节点
      assignNode: {},
      addEvaluateList: {
        list: [],
        total_count: 0
      },
      //选中的list
      getRowKeys (row) {
        //记录每行的key值
        return row.person_id;
      },
      dialogTableVisible: false,
      startrequestParam: {
        comp_id: '',
      }
    }
  },
  methods: {
    judgeJobPersonIsExist (item) {
      let isExsit = false;
      this.selPersonArr.map((item1) => {
        if (item.person_id == item1.person_id) {
          isExsit = true;
        }
      });
      if (isExsit == false) {
        this.selPersonArr.unshift(item);
      };
      this.$message.success('操作成功')
    },
    joinClick () {//参与
      if (this.multipleArr.length > 0) {
        if (this.selPersonArr.length == 0) {
          this.selPersonArr = Object.assign([], this.multipleArr);//拷贝
          console.log('00000测试selPersonArr=', this.selPersonArr)
        } else {//下面已有参与人员
          this.multipleArr.map(async (item) => {
            await this.judgeJobPersonIsExist(item);//评价岗位人员是否已经存在了
          })
        };
        this.$message.success('操作成功')
      } else {
        this.$message.warning('参与人员不能为空')
      };
    },
    getPersonIds () {
      let arr = [];
      if (this.selPersonArr.length > 0) {
        this.selPersonArr.map(item => {
          arr.push(item.person_id)
        })
      };
      return arr.length > 0 ? arr.join(',') : '';
    },
    getParams () {
      let objParam = {
        title: this.personRequestParams.title,
        exercise_id: this.personRequestParams.exercise_id,
        job_name: this.personRequestParams.job_name,
        inside_evaluate: this.requestParams.eva_person,
        person_ids: this.getPersonIds()
      };
      return objParam;
    },
    onSure () {
      backEvaluateApi.saveByJob({
        data: this.getParams()
      }).then((res) => {
        if (res.code == 0) {
          this.$emit('update:personRequestParams', {})
          this.$message.success('操作成功')
        }
      }).catch((error) => {
        console.log(error)
      })
    },

    delPerson (row, i) {//删除人员
      this.$refs.multipleTable.toggleRowSelection(row, false);//取消状态
      this.selPersonArr.splice(i, 1);//删除
      this.$message.success('删除成功');
    },
    onDelClick (item, i) {//删除
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        left: true
      }).then(() => {
        this.delPerson(item, i);//删除人员
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取列表
    getAccountList () {
      let storage = window.localStorage.getItem('userInfo') || '{}';
      let userInfo = JSON.parse(storage);
      accountApi.getDeptUserList({
        data: {
          company_id: userInfo.comp_id,
          dept_no: userInfo.dept_no,
          type: 1,
          all_status: '1',
          is_page: 1,
          page: this.requestParam.page,
          page_size: this.requestParam.page_size,
          user_name: this.user_name
        }
      }).then(res => {
        let data = res.data;
        if (data) {
          this.accountListData.list = data.list;
          this.accountListData.total_count = data.total_count;//总数
        }
      })
    },
    //人员列表
    getPersonList () {
      backEvaluateApi.getPersonList({
        params: this.requestParam
      }).then((res) => {
        if (res.code === 0) {
          this.addEvaluateList = res.data
        }
      }).catch(err => {
        console.log(err);
      })
    },
    selectChange (selection, row) {
      this.multipleArr = selection;
      console.log(selection, row, '-----------')
      // let selected = selection.length && selection.indexOf(row) !== -1;
      // //selected是当前点击的选中态
      // //选中的表格取消事件
      // if (selected === false) {
      //   this.$nextTick(() => {
      //     this.$refs.multipleTable.selection.forEach((ele) => {
      //       if (ele.person_id == row.person_id) {
      //         this.$refs.multipleTable.toggleRowSelection(ele, false);
      //       }
      //     });
      //   });
      // }
    },
    handleAddSizeChange (val) {
      this.requestParam.page_size = val;
      this.handleAddPageChange(1);//刷新
    },
    //分页-新增被评价人
    handleAddPageChange (val) {
      this.requestParam.page = val;
      this.getPersonList();//列表
    },
    // handleSelectionChange (rows) {
    //   this.checkIds = []
    //   rows.forEach(item => {
    //     this.checkIds.push(item.person_id)
    //     //去重
    //     this.checkIds = Array.from(new Set(this.checkIds))
    //   });
    // },
    cancelEvaluate () {//取消
      this.initResetCommonFunc();//初始化通知函数
    },
    initResetCommonFunc () {//初始化通知函数
      this.addOrgan = this.$options.data().addOrgan;//重置
      this.$emit('update:childDialog', false);
    },
    saveAddEvaluate () {//确定
      let ids = this.checkIds.join(',')
      backEvaluateApi.saveAddpeople({
        data: {
          person_ids: ids
        }
      }).then((res) => {
        if (res.code === 0) {
          this.$message.success('添加成功');
          this.initResetCommonFunc();//重置
        }
      }).catch(err => {
        console.log(err);
      })
    },
    //关闭弹窗
    closeAdd () {
      this.$refs.multipleTable.clearSelection();
      this.checkIds = [];
      this.initResetCommonFunc();//初始化通知函数
    },
    initFunc () {//初始化
      this.requestParams = Object.assign({}, this.personRequestParams);
      this.getPersonList();//人员列表
    }
  },
  watch: {
    selectedNode (n, o) {
      if (n.node_id_desc && n.node_id_desc != o.node_id_desc) {//node_id_desc存在
        this.requestParam.node_id = n.node_id || '';
        this.requestParam.node_type = n.node_type || '';
        this.handleAddPageChange(1);//刷新
      }
    },
    childDialog (n, o) {
      if (n == true) {
        this.initFunc();
      };
      this.dialogTableVisible = n;
    }
  },
  created () {
    this.initFunc();//初始化
    this.dialogTableVisible = this.childDialog;
  }
}
</script>

<style lang="scss" scoped>
.sel-eva-posite-container {
  .bottom-box {
    margin-top: 20px !important;
  }
}
.left-tree {
  padding-right: 20px;
}
.title-style {
  line-height: 40px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.divide-style {
  margin-bottom: 20px;
}
.margin-style {
  margin-bottom: 0px;
}
.judge-job-person {
  margin-top: 20px;
  height: 40px;
  line-height: 40px;
  color: white;
  background-color: rgba(129, 211, 248, 1);
}
.ul-box-style {
  width: 100%;
  height: 300px;
  overflow-y: auto;
  margin-top: 20px;
  padding: 0px 20px;
  ul {
    li {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      height: 40px;
      line-height: 40px;
      span {
        cursor: pointer;
      }
    }
  }
}
.oper-button {
  margin-top: 20px;
  text-align: center;
}
</style>